package com.cuijiao.emp.java;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * @author cuijiao 对象流，ObjectOutputStream可用于对象的持久化操作
 */
public class ObjectStream {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) {
        // 写对象
        // writeObject();
        // 读对象
        readObject();
    }

    /**
     *
     * 对象必须序列化并有序列号
     */
    private static void readObject() {
        // TODO Auto-generated method stub
        File file = new File("D:\\data\\test.log");
        if (!file.exists()) {
            return;
        }
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Emp emp = null;
        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            try {
                emp = (Emp) ois.readObject();// 读到最后无数据时，不是返回对象而是报EOFException
                while (emp != null) {
                    System.out.println(emp);
                    emp = (Emp) ois.readObject();
                }
            } catch (EOFException e) {
                // EOFException异常，表示读数据结束，不需要任何操作
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 序列化，对于需要用writeObject写入文件的对象，必须要实现序列化
     */
    private static void writeObject() {
        File file = new File("D:\\data\\test.log");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        Emp emp = new Emp("lisa", "e001", 888, true, new Date());

        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(emp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
